<template>
  <div>
    <BreakSpace label="关爱任务设置" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="formPanel"
      :cols="3"
      :labelWidth="110"
      :list="formList"
      :formType="type"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
      style="margin-top: 20px"
    />

    <BreakSpace label="关爱对象范围" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="careObjPanel"
      :columns="careObjColumns"
      :isSelectColumn="true"
      :dataSource="dataSource"
      :height="'auto'"
      columnsRef="ysjManualCareTaskPanelTable"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button
          size="small"
          :disabled="isAdd"
          type="primary"
          icon="el-icon-plus"
          @click="addHandle"
        >新增</el-button>
        <el-button
          size="small"
          :disabled="isChoice"
          type="primary"
          icon="el-icon-delete"
          @click="deleteHandle"
        >删除</el-button>
      </template>
    </FilterTable>

    <BreakSpace label="关爱人员设置" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="carUserPanel"
      :cols="4"
      :labelWidth="110"
      :list="careEmp"
      :formType="type"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
      style="margin-top: 20px"
    />
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog(false)">取 消</el-button>
      <el-button v-if="type !== 'show'" @click="saveDialog" type="primary">{{ btnText }}</el-button>
    </div>

    <BaseDialog
      :visible.sync="dialogVisible"
      title="选择关爱对象"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '10px' }"
      destroyOnClose
    >
      <SelectCareObj @fatherReq="reqProblem" @fatherGoBack="goBackProblem" />
    </BaseDialog>
  </div>
</template>
<script>
import { getCateTaskById, saveCareTask } from '@/api/customerCare/visitRules/manualCareTask';
import { templateType } from '@/api/customerCare/visitRules/SMSTemplate';
import { getUserInfoByRole, getUserInfo } from '@/api/customerCare/saleVisit/careTaskSearch';
import { dictionary } from '@/utils/dictMixin';
import { formatdate } from '@/utils/index';
import SelectCareObj from './selectCareObj';

export default {
  name: 'ManualCareTaskPanel',
  mixins: [dictionary],
  components: { SelectCareObj },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    recordVersion: String,
    carePlanId: {
      type: String,
      default: ''
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    this.saveData = null;
    return {
      formList: this.createFormList(),
      careObjColumns: this.createTableColumns(),
      careEmp: this.createCareEmp(),
      dataSource: [],
      fetchParams: {},
      careTypes: [],
      isAdd: false,
      isChoice: true,
      dialogVisible: false,
      selectedRows: [],
      careTargetList: [],
      employeeIdList: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if (this.type === 'show') {
        this.isAdd = true;
      }
      if (this.type != 'add') {
        getCateTaskById(this.carePlanId).then(res => {
          if (res.resultCode == 200) {
            this.formList.forEach(x => {
              x.initialValue = res.data[x.fieldName];
            });
            this.dataSource = res.data['careTargetList'];

            this.careEmp.find(item => item.fieldName === 'careEmpType').initialValue = res.data['careEmpType'];
            if (res.data['careEmpType'] == 15951001) {
              this.careEmp.find(item => item.fieldName === 'employeeIdList').disabled = true;
            }
            let employeeIds = res.data['employeeIdList'];
            let ids = [];
            for (let i = 0; i < employeeIds.length; i++) {
              ids.push(parseInt(employeeIds[i]));
            }
            this.careEmp.find(item => item.fieldName === 'employeeIdList').initialValue = ids;
          } else {
            this.$message.error('获取关爱对象范围失败!');
          }
        });
      }
      //初始化关爱人员选择列表
      getUserInfo().then(res => {
        if (res.resultCode == 200) {
          let param = {
            companyId: res.data.userInfo.companyId,
            positionCode: '10061010'
          };
          getUserInfoByRole(param).then(res => {
            if (res.resultCode == 200) {
              this.careEmp[1].itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
            } else {
              this.$message.error('获取关爱人员列表失败!');
            }
          });
        } else {
          this.$message.error('获取当前登录用户信息失败!');
        }
      });
      //获取短信模板下拉数据
      templateType({ smsTemplateType: 15721006 }).then(res => {
        if (res.resultCode == 200) {
          this.smsTemplateList = res.data.map(x => ({ value: x.smsTemplateId, text: x.smsTemplateName }));
          this.formList[4].itemList = this.smsTemplateList;
        } else {
          this.$message.error('获取短信模板失败!');
          return;
        }
      });
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '计划编号',
          fieldName: 'planNo',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '关爱类型',
          fieldName: 'careTypeCode',
          placeholder: '请选择',
          itemList: [{ text: '活动邀约', value: 15721006 }],
          rules: [{ required: true, message: '请选择关爱类型', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '关爱名称',
          fieldName: 'careName',
          initialValue: '',
          rules: [{ required: true, message: '请填写关爱名称', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '模板类型',
          fieldName: 'careWay',
          itemList: [{ text: '电话', value: 15871003 }]
        },
        {
          type: 'SELECT',
          label: '模板名称',
          fieldName: 'templateName',
          itemList: []
        },
        {
          type: 'DATE',
          label: '要求完成日期',
          fieldName: 'requiredDate',
          dateType: 'exactdate',
          minDateTime: formatdate(new Date(), 1),
          /* format: "yyyy-MM-dd",
          minDateTime: formatdate(new Date(),1), */
          rules: [{ required: true, message: '请选择要求完成日期', trigger: 'blur' }]
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '员工ID',
          dataIndex: 'potentialCustomersId',
          sorter: true,
          filter: true,
          hidden: true,
          filterType: 'input'
        },
        {
          title: '销售顾问ID',
          dataIndex: 'consultant',
          sorter: true,
          filter: true,
          hidden: true,
          filterType: 'input'
        },
        {
          title: '客户编号',
          dataIndex: 'potentialCustomerNo',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '手机号',
          dataIndex: 'mobilePhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultantName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '建档日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '出库日期',
          dataIndex: 'stockInOutDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.gender, '1002')}</div>;
          }
        },
        {
          title: '出生日期',
          dataIndex: 'birthday',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.customerType, '1523')}</div>;
          }
        },
        {
          title: '客户来源',
          dataIndex: 'clueSourceName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '意向级别',
          dataIndex: 'intentLevel',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.intentLevel, '1519')}</div>;
          }
        }
      ];
    },
    addHandle() {
      this.dialogVisible = true;
    },
    deleteHandle() {
      this.selectedRows.map(x => {
        this.dataSource = this.dataSource.filter(item => item.$index !== x.$index);
      });
    },
    selectChange(rows) {
      //选中时触发的函数
      this.selectedRows = rows;
      if (this.selectedRows.length > 0) {
        this.isChoice = false;
      } else {
        this.isChoice = true;
      }
    },
    createCareEmp() {
      return [
        {
          type: 'RADIO',
          label: '分配规则',
          fieldName: 'careEmpType',
          selfCols: 2,
          itemList: this.createDictList('1595'),
          initialValue: 15951002,
          change: val => {
            if (val == 15951001) {
              this.careEmp.find(item => item.fieldName === 'employeeIdList').disabled = true;
              this.careEmp.find(item => item.fieldName === 'employeeIdList').initialValue = [];
            } else {
              this.careEmp.find(item => item.fieldName === 'employeeIdList').disabled = false;
            }
          }
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '关爱人员',
          fieldName: 'employeeIdList',
          disabled: false,
          selfCols: 4,
          itemList: []
        }
      ];
    },
    //过滤CODE下拉值
    filterDict(codeStr, dict) {
      if (codeStr && codeStr != '') {
        let dictList = this.createDictList(dict);
        let res = [];
        for (let i = 0; i < dictList.length; i++) {
          if (codeStr.indexOf(dictList[i].value) != -1) {
            res.push(dictList[i]);
          }
        }
        return res;
      }
      return '';
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    closeDialog(refresh) {
      if (refresh) {
        this.$emit('changeHandle', {});
      }
      this.$emit('close', false);
    },
    goBackProblem() {
      this.dialogVisible = false;
    },
    reqProblem(data) {
      let localIds = '';
      this.dataSource.forEach(data => {
        localIds += data.potentialCustomersId + ',';
      });
      for (var i = 0; i < data.length; i++) {
        if (!(localIds.indexOf(data[i].potentialCustomersId) != -1)) {
          let vat = {
            potentialCustomerNo: data[i].potentialCustomerNo,
            customerName: data[i].customerName,
            mobilePhone: data[i].mobilePhone,
            consultantName: data[i].consultantName,
            consultant: data[i].consultant,
            createdAt: data[i].createdAt,
            stockInOutDate: data[i].stockInOutDate,
            gender: data[i].gender,
            birthday: data[i].birthday,
            customerType: data[i].customerType,
            clueSourceName: data[i].clueSourceName,
            clueName: data[i].clueName,
            intentLevel: data[i].intentLevel,
            potentialCustomersId: data[i].potentialCustomersId
          };
          this.employeeIdList.push(data[i].consultant);
          this.careTargetList.push(data[i].potentialCustomersId);
          this.dataSource.push(vat);
        }
      }

      this.goBackProblem();
    },
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let cTList = [];
      let empIdList = [];
      this.dataSource.forEach(data => {
        cTList.push(data.potentialCustomersId);
        empIdList.push(data.consultant);
      });
      this.saveData.careTargetList = cTList;
      const type = this.careEmp.find(item => item.fieldName === 'careEmpType').initialValue;
      this.saveData.careEmpType = type;
      if (this.saveData.requiredDate && this.saveData.requiredDate != '') {
        this.saveData.requiredDate = this.saveData.requiredDate.substring(0, 10);
      }
      if (type === 15951001) {
        this.saveData.employeeIdList = empIdList;
      } else {
        this.saveData.employeeIdList = this.careEmp.find(item => item.fieldName === 'employeeIdList').initialValue;
      }
      if (this.saveData !== null) {
        let res = {};
        if (this.type === 'edit') {
          this.saveData.carePlanId = this.carePlanId;
          this.saveData.recordVersion = this.recordVersion;
        }
        res = await saveCareTask(this.saveData, this.empId);

        if (res.resultCode === 200) {
          this.closeDialog(true);
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
.dialog-form {
  width: 100%;
  margin: 0;
}

.el-checkbox-group .el-checkbox + .el-checkbox {
  margin: 0;
}

.box {
  border: 1px solid @borderColor;
  border-radius: @borderRadius;
  box-shadow: @boxShadow;
  padding: @modulePadding;
  margin-top: 20px;
}
</style>
